package com.css.devops.component;

import java.nio.charset.StandardCharsets;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.css.devops.config.JenkinsProperties;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

@Service
public class JenkinsBasicComponent {

	@Autowired
	private JenkinsProperties jenkinsProperties;
	
	/**
	 * Jenkins get请求
	 * @param requestUrl
	 * @return
	 */
	public HttpResponse getRequest(String requestUrl) {
        return getRequest(requestUrl, null);
	}
	
	/**
	 * Jenkins get请求
	 * @param requestUrl
	 * @param formMaps
	 * @return
	 */
	public HttpResponse getRequest(String requestUrl,Map<String,Object> formMaps) {
		String endUrl = jenkinsProperties.getUrl() + requestUrl;
		String basicAuth = HttpHeaders.encodeBasicAuth(jenkinsProperties.getUsername(), jenkinsProperties.getPassword(), StandardCharsets.UTF_8);
		HttpRequest request = HttpRequest.get(endUrl).header(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
		if(!CollectionUtils.isEmpty(formMaps)) {
			request.form(formMaps);
		}
        HttpResponse response = request.execute();
        return response;
	}
	
	/**
	 * Jenkins post请求
	 * @param requestUrl
	 * @return
	 */
	public HttpResponse postRequest(String requestUrl,Map<String, String> formMapStr) {
        return postRequest(requestUrl, formMapStr, null);
	}

	/**
	 * Jenkins post请求
	 * @param requestUrl
	 * @return
	 */
	public HttpResponse postRequest(String requestUrl, Map<String, String> formMapStr,Map<String, String> headers) {
		String endUrl = jenkinsProperties.getUrl() + requestUrl;
		String basicAuth = HttpHeaders.encodeBasicAuth(jenkinsProperties.getUsername(), jenkinsProperties.getPassword(), StandardCharsets.UTF_8);
		HttpRequest request = HttpRequest.post(endUrl).header(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
		if(!CollectionUtils.isEmpty(formMapStr)) {
			request = request.formStr(formMapStr);
		}
		if(!CollectionUtils.isEmpty(headers)) {
			request = request.addHeaders(formMapStr);
		}
		request = request.addHeaders(formMapStr);
        HttpResponse response = request.execute();
        return response;
	}
}
